<template>
  <div class="order-list">
    <el-select v-model="filterStatus" placeholder="选择订单状态">
      <el-option
          v-for="status in orderStatusList"
          :key="status.value"
          :label="status.label"
          :value="status.value"
      />
    </el-select>
    <el-table :data="filteredOrderList" style="width: 100%">
      <el-table-column label="订单号" prop="orderNo"/>
      <el-table-column label="餐厅名称" prop="restaurant.name"/>
      <el-table-column label="用户信息" width="100">
        <template #default="{ row }">
          <el-popover placement="top" trigger="hover">
            <template #reference>
              <img :src="row.user.avatar_url" alt="用户头像" style="width: 32px; height: 32px">
            </template>
            <p>昵称:{{ row.user.nickname }}</p>
          </el-popover>
        </template>
      </el-table-column>

      <el-table-column label="总金额">
        <template #default="{ row }">
          {{ row.totalAmount.toFixed(2) }}元
        </template>
      </el-table-column>
      <el-table-column label="下单时间">
        <template #default="{ row }">
          {{ formatDateTime(row.createTime) }}
        </template>
      </el-table-column>
      <el-table-column label="更新时间">
        <template #default="{ row }">
          {{ formatDateTime(row.updateTime) }}
        </template>
      </el-table-column>
      <el-table-column label="订单状态" prop="status">
        <template #default="{ row }">
          <el-tag :type="statusTagType(row.status)">{{ statusLabel(row.status) }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="订单备注" width="100">
        <template #default="{ row }">
          <el-popover placement="top" trigger="hover">
            <template #reference>
              订单备注
            </template>
            <p>{{ row.remark }}</p>
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column label="查看详情">
        <template #default="{ row }">
          <el-button size="small" @click="handleViewDishList(row.dishList)">查看详情</el-button>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="150">
        <template #default="{ row }">
          <el-button size="small" type="primary" @click="handleEditOrder(row)">编辑</el-button>
          <el-button size="small" type="danger" @click="handleDeleteOrder(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页器 -->
    <div class="pagination">
      <el-pagination
          :total="total"
          layout="total,sizes, prev, pager, next"
          :page-sizes="[10, 20, 50]"
          @current-change="handleCurrentChange"
          @size-change="handleSizeChange"
      />
    </div>
    <!-- 订单详情弹窗 -->
    <el-dialog title="订单详情" v-model="showDishListDialog">
      <el-table :data="currentDishList" style="width: 100%">
        <el-table-column label="菜品名称" prop="name"/>
        <el-table-column label="单价" prop="price"/>
        <el-table-column label="数量" prop="count"/>
        <el-table-column label="小计" :formatter="formatSubtotal"/>
      </el-table>
    </el-dialog>
    <!-- 编辑订单弹窗 -->
    <el-dialog title="编辑订单" v-model="showEditOrderDialog">
      <el-form :model="currentOrder" label-position="right" label-width="80px">
        <el-form-item label="订单号">
          <el-input v-model="currentOrder.orderNo" disabled/>
        </el-form-item>
        <el-form-item label="总金额">
          <el-input v-model="currentOrder.totalAmount"/>
        </el-form-item>
        <el-form-item label="订单状态">
          <el-select v-model="currentOrder.status">
            <el-option
                v-for="status in orderStatusList"
                :key="status.value"
                :label="status.label"
                :value="status.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="餐厅">
          <el-select v-model="currentOrder.restaurantId">
            <el-option
                v-for="restaurant in restaurantList"
                :key="restaurant.id"
                :label="restaurant.name"
                :value="restaurant.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="菜品列表">
          <el-table :data="currentOrder.dishList" style="width: 100%">
            <el-table-column label="菜品名称" prop="name"/>
            <el-table-column label="单价" prop="price"/>
            <el-table-column label="数量" prop="count">
              <template #default="{ row }">
                <el-input v-model="row.count" type="number" min="1"/>
              </template>
            </el-table-column>
            <el-table-column label="小计" :formatter="formatSubtotal"/>
            <el-table-column label="操作">
              <template #default="{ row }">
                <el-button type="danger" size="small" @click="handleDeleteDish(row)">
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="currentOrder.remark" type="textarea" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSaveOrder">保存</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import {reactive, ref, onMounted, computed, toRefs} from "vue";
import dayjs from "dayjs";
import {ElMessage, ElMessageBox} from "element-plus";
import {deleteOrder, getOrderDetail, getOrderList, updateOrder} from "@/api/order";
import {getRestaurantList} from "@/api/restaurant";

export default {
  setup() {
    const orderList = ref([]);
    const orderStatusList = reactive([
      {label: "全部", value: "all"},
      {label: "未支付", value: "0"},
      {label: "已支付", value: "1"},
      {label: "正在制作", value: "2"},
      {label: "已上菜", value: "3"}
    ]);
    // 过滤状态
    const filterStatus = ref('all');
    // 过滤后的订单列表
    const filteredOrderList = computed(() => {
      if (filterStatus.value === "all") {
        return orderList.value;
      } else {
        return orderList.value.filter((order) => order.status === filterStatus.value);
      }
    });
    // 显示编辑订单弹窗
    const showDishListDialog = ref(false);
    // 显示订单详情弹窗
    const currentDishList = reactive([]);
    // 格式化时间
    const formatDateTime = (value) => {
      return dayjs(value).format("YYYY-MM-DD");
    };
    // 订单状态
    const statusLabel = (status) => {
      const matchedStatus = orderStatusList.find((s) => s.value === status);
      return matchedStatus ? matchedStatus.label : "";
    };
    // 订单状态标签类型
    const statusTagType = (status) => {
      switch (status) {
        case "0":
          return "danger";
        case "1":
          return "success";
        case "2":
          return "warning";
        case "3":
          return "info";
        default:
          return "";
      }
    };
    // 查看订单详情
    const handleViewDishList = (dishList) => {
      currentDishList.splice(0, currentDishList.length, ...dishList);
      showDishListDialog.value = true;
    };
    // 编辑订单
    const handleEditOrder = async (row) => {
      const id = row.id;
      const {data} = await getOrderDetail(id);
      currentOrder.value = data;
      showEditOrderDialog.value = true;
    };
    // 保存订单
    const handleSaveOrder = async () => {
      const {id, ...rest} = currentOrder.value;
      rest.dishList = JSON.stringify(rest.dishList);
      await updateOrder(id, rest);
      ElMessage.success("保存成功");
      showEditOrderDialog.value = false;
      currentOrder.value = {};
      await fetchOrderList();
    }
    // 删除订单
    const handleDeleteOrder = (row) => {
      ElMessageBox.confirm('确定删除该订单吗?', '提示', {
        type: 'warning',
      }).then(async () => {
        try {
          await deleteOrder(row.id)
          ElMessage.success('删除成功')
          await fetchOrderList()
        } catch (e) {
          ElMessage.error('删除失败')
          console.log(e)
        }
      }).catch(() => {
        ElMessage.info('已取消删除')
      })
    };
    // 计算小计
    const formatSubtotal = ({price, count}) => {
      return `￥${price * count}`;
    };
    const state = reactive({
      currentPage: 1,
      pageSize: 10,
      total: 0
    })
    // 分页器当前页码变化回调
    const handleCurrentChange = (currentPage) => {
      state.currentPage = currentPage
      fetchOrderList()
    }
    // 分页器页码大小变化回调
    const handleSizeChange = (pageSize) => {
      state.pageSize = pageSize
      fetchOrderList()
    }
    // 菜品列表编辑
    const handleDeleteDish = (row) => {
      const index = currentOrder.value.dishList.findIndex((dish) => dish.dishId === row.dishId);
      if (index !== -1) {
        currentOrder.value.dishList.splice(index, 1);
      }
    };
    // 获取订单列表
    const fetchOrderList = async () => {
      const res = await getOrderList(state.currentPage, state.pageSize);
      orderList.value = res.data.list;
      state.total = res.data.total;
    }
    const restaurantList = ref([])
    // 获取餐厅数据
    const getRestaurants = async () => {
      try {
        const response = await getRestaurantList()
        if (response.msg === '请求成功') {
          restaurantList.value = response.data
        } else {
          ElMessage.error('获取餐厅数据失败')
        }
      } catch (e) {
        ElMessage.error('获取餐厅数据失败')
        console.log(e)
      }
    }
    // 订单编辑弹窗
    const showEditOrderDialog = ref(false);
    const currentOrder = ref({});

    onMounted(() => {
      fetchOrderList();
      getRestaurants()
    });
    // 订单列表
    return {
      ...toRefs(state),
      orderList,
      orderStatusList,
      filterStatus,
      showDishListDialog,
      formatDateTime,
      statusLabel,
      statusTagType,
      handleViewDishList,
      handleEditOrder,
      handleDeleteOrder,
      currentDishList,
      formatSubtotal,
      showEditOrderDialog,
      currentOrder,
      filteredOrderList,
      handleSaveOrder,
      restaurantList,
      handleCurrentChange,
      handleSizeChange,
      handleDeleteDish
    };
  },
};
</script>

<style>
.order-list {
  padding: 20px;
}
</style>
